const path = require("node:path");
const { exec_shell } = require("./shell_tool");
const { which } = require("./which_tool");

/**
 * 查找指定软件的安装目录
 * @param {*} target
 * @returns
 */
async function registerSearchInstallLocation(target) {
    const key = target;
    var Uninstalls = [
        "HKEY_CURRENT_USER\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall",
        "HKEY_LOCAL_MACHINE\\SOFTWARE\\WOW6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall",
    ];
    var result = "";
    for (var i = 0; i < Uninstalls.length; i++) {
        const Uninstall = Uninstalls[i];
        result = await registerQuery(`${Uninstall}\\${key}`);
        if (result) break;
    }
    const InstallLocation = registerGetProp(result, "InstallLocation");
    if (InstallLocation) return InstallLocation;
    const UninstallString = registerGetProp(result, "UninstallString");
    if (UninstallString) return path.dirname(UninstallString);
    return "";
}

/**
 * 查找指定注册项
 * @param {*} key
 * @returns
 */
async function registerQuery(key) {
    const REG_EXE = await which("reg");
    return exec_shell({
        cmd: [REG_EXE, "QUERY", key],
        capture_stdout: true,
        ignore_code: true,
        quiet: true,
    });
}

/**
 * 获取注册项的属性
 * @param {*} queryResult
 * @param {*} key
 * @returns
 */
function registerGetProp(queryResult, key) {
    var matches = queryResult.match(new RegExp(`${key}\\s+REG_SZ\\s+(.*)`));
    if (matches && matches.length > 1) {
        var value = matches[1];
        if (value.startsWith('"') && value.endsWith('"')) {
            return value.substring(1, value.length - 1);
        }
        return value;
    }
    return "";
}

module.exports = {
    registerSearchInstallLocation,
    registerGetProp,
    registerQuery,
};
